var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
const Canting = require('../../database/connacting');
const path = require('path');
const fs = require('fs');
/* GET home page. */
// 支持搜索和分类筛选的商品列表接口
router.get('/datalist', async (req, res) => {
  try {
    const { search = '', category = '', categoryLike = '' } = req.query;
    const query = {};
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } }
      ];
    }
    if (category) {
      query.category = category;
    }
    if (categoryLike) {
      query.category = { $regex: categoryLike, $options: 'i' };
    }
    const dataList = await Canting.find(query);
    res.send({
      code: 200,
      data: dataList
    });
  } catch (err) {
    res.status(500).send({ code: 500, msg: '数据库查询失败', error: err });
  }
});

// 新增商品
router.post('/add', async (req, res) => {
  try {
    const newProduct = await Canting.create(req.body);
    res.send({ code: 200, data: newProduct });
  } catch (err) {
    res.status(500).send({ code: 500, msg: '新增失败', error: err });
  }
});

// 删除商品
router.delete('/delete/:id', async (req, res) => {
  try {
    const result = await Canting.deleteOne({ id: Number(req.params.id) });
    res.send({ code: 200, data: result });
  } catch (err) {
    res.status(500).send({ code: 500, msg: '删除失败', error: err });
  }
});

// 修改商品
router.put('/update/:id', async (req, res) => {
  try {
    const updated = await Canting.findOneAndUpdate({ id: Number(req.params.id) }, req.body, { new: true });
    res.send({ code: 200, data: updated });
  } catch (err) {
    res.status(500).send({ code: 500, msg: '修改失败', error: err });
  }
});

// 修改待审核状态
router.patch('/pending/:id', async (req, res) => {
  try {
    const updated = await Canting.findOneAndUpdate({ id: Number(req.params.id) }, { pending: req.body.pending }, { new: true });
    res.send({ code: 200, data: updated });
  } catch (err) {
    res.status(500).send({ code: 500, msg: '状态修改失败', error: err });
  }
});

// 获取所有商品分类（去重）
router.get('/categories', async (req, res) => {
  try {
    const categories = await Canting.distinct('category');
    res.send({ code: 200, data: categories });
  } catch (err) {
    res.status(500).send({ code: 500, msg: '分类获取失败', error: err });
  }
});

// 图片上传接口
router.post('/upload', (req, res) => {
  const form = new multiparty.Form({ uploadDir: path.join(__dirname, '../../public/images/products') });
  form.parse(req, (err, fields, files) => {
    if (err) {
      return res.status(500).send({ code: 500, msg: '上传失败', error: err });
    }
    const file = files.file[0];
    // 生成唯一文件名
    const ext = path.extname(file.originalFilename || file.path);
    const newFilename = Date.now() + ext;
    const newPath = path.join(form.uploadDir, newFilename);
    fs.renameSync(file.path, newPath);
    // 返回图片可访问的URL
    const url = `/images/products/${newFilename}`;
    res.send({ code: 200, url });
  });
});


module.exports = router;


// [
//   // 食品类
//   { id: 1, name: '经典套餐', price: 15.99, stock: 200, category: '套餐', brand: '美食坊', description: '包含主菜、饮料和小吃', image: './致谢.png', pending: false },
//   { id: 2, name: '奶茶', price: 8.50, stock: 150, category: '饮品', brand: '茶语', description: '经典原味奶茶，可选甜度', image: './致谢.png', pending: false },
//   { id: 3, name: '炒饭', price: 12.00, stock: 80, category: '主食', brand: '饭香', description: '鸡蛋、火腿、蔬菜炒制', image: './致谢.png', pending: false },
//   { id: 4, name: '水果沙拉', price: 10.50, stock: 120, category: '小吃', brand: '鲜果时光', description: '当季新鲜水果混合', image: './致谢.png', pending: false },
//   { id: 5, name: '炸鸡桶', price: 22.00, stock: 180, category: '小吃', brand: '快乐鸡', description: '5块炸鸡配特制酱料', image: './致谢.png', pending: false },
//   { id: 6, name: '牛肉面', price: 18.00, stock: 95, category: '主食', brand: '面之道', description: '大块牛肉配手工面条', image: './致谢.png', pending: false },
//   { id: 7, name: '冰咖啡', price: 12.50, stock: 200, category: '饮品', brand: '咖啡工坊', description: '现磨咖啡加冰块', image: './致谢.png', pending: false },
//   { id: 8, name: '蔬菜春卷', price: 6.00, stock: 150, category: '小吃', brand: '亚洲风味', description: '胡萝卜、白菜等蔬菜卷', image: './致谢.png', pending: false },
//   { id: 9, name: '海鲜披萨', price: 32.00, stock: 75, category: '主食', brand: '披萨屋', description: '虾、鱿鱼、蟹肉配芝士', image: './致谢.png', pending: false },
//   { id: 10, name: '巧克力蛋糕', price: 14.00, stock: 110, category: '甜点', brand: '甜蜜时光', description: '浓郁巧克力口味', image: './致谢.png', pending: false },

//   // 数码产品类
//   { id: 11, name: '无线蓝牙耳机', price: 199.00, stock: 50, category: '数码配件', brand: '声悦', description: '高解析音质，降噪功能，续航30小时', image: './earphone.png', pending: false },
//   { id: 12, name: '移动电源', price: 59.90, stock: 80, category: '数码配件', brand: '电霸', description: '10000mAh，支持快充，双USB输出', image: './powerbank.png', pending: false },
//   { id: 13, name: '智能手表', price: 299.00, stock: 30, category: '可穿戴设备', brand: '时迹', description: '心率监测，50米防水，2周续航', image: './smartwatch.png', pending: false },

//   // 家居用品类
//   { id: 14, name: '香薰蜡烛', price: 29.90, stock: 120, category: '家居装饰', brand: '香氛生活', description: '天然大豆蜡，薰衣草香味，45小时燃烧', image: './candle.png', pending: false },
//   { id: 15, name: '记忆棉枕头', price: 89.00, stock: 60, category: '床上用品', brand: '舒梦', description: '人体工学设计，缓解颈部压力', image: './pillow.png', pending: false },
//   { id: 16, name: '多功能料理机', price: 299.00, stock: 25, category: '厨房电器', brand: '厨艺大师', description: '绞肉、榨汁、研磨一机多用', image: './blender.png', pending: false },

//   // 美妆个护类
//   { id: 17, name: '玻尿酸精华液', price: 129.00, stock: 40, category: '护肤品', brand: '水光肌', description: '深层补水，24小时保湿', image: './serum.png', pending: false },
//   { id: 18, name: '电动牙刷', price: 159.00, stock: 50, category: '个人护理', brand: '洁齿宝', description: '5种刷牙模式，智能压力感应', image: './toothbrush.png', pending: false },
//   { id: 19, name: '持久不脱色口红', price: 89.00, stock: 70, category: '彩妆', brand: '魅色', description: '丝绒质地，12小时持妆', image: './lipstick.png', pending: false },

//   // 图书文具类
//   { id: 20, name: '钢笔礼盒', price: 199.00, stock: 35, category: '文具', brand: '书写人生', description: '18K金笔尖，实木礼盒包装', image: './pen.png', pending: false },
//   { id: 21, name: '编程入门书籍', price: 59.00, stock: 90, category: '图书', brand: '图灵出版', description: 'Python编程从入门到实践', image: './book.png', pending: false },

//   // 运动户外类（原数据未包含，示例补充）
//   // { id: 22, name: '瑜伽垫', price: 49.00, stock: 60, category: '运动器材', brand: '瑜伽生活', description: '环保TPE材质，防滑设计', image: './mat.png', pending: false },
//   // { id: 23, name: '登山背包', price: 259.00, stock: 20, category: '户外装备', brand: '探险者', description: '50L容量，防水耐磨', image: './backpack.png', pending: false },

//   // 服饰配件类
//   { id: 24, name: '太阳镜', price: 129.00, stock: 45, category: '配饰', brand: '视界', description: 'UV400防护，时尚偏光镜片', image: './sunglasses.png', pending: false },
//   { id: 25, name: '纯棉T恤', price: 39.00, stock: 100, category: '服装', brand: '舒适派', description: '100%纯棉，多种颜色可选', image: './tshirt.png', pending: false }
// ]